package com.example.replacebooks.controller;

import cn.hutool.core.date.DateUtil;
import com.example.replacebooks.common.Result;
import com.example.replacebooks.entity.Orders;
import com.example.replacebooks.entity.Params;
import com.example.replacebooks.service.OrderService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin //解决跨域问题
@RestController
@RequestMapping("/order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;

    @GetMapping
    public Result findAll(){return Result.success(orderService.findAll());}

    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Orders> info = orderService.findBySearch(params);
        return Result.success(info);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Orders orders){
        orderService.add(orders);
        return Result.success();
    }

    @PostMapping("/addcart")
    public Result addcart(@RequestBody Orders orders){
        // 更新购物车里相同的商品数量
        Integer bookid = orders.getBookid();
        Integer userid = orders.getUserid();
        Orders orders1 = orderService.findByBookidAndUserid(bookid, userid);
        if (orders1 != null){
            orders1.setNum(orders1.getNum() + orders.getNum());
            orders1.setCreatetime(DateUtil.now());
            orderService.UpdateByOrderid(orders1);
            return Result.success();
        }else{
            // 新增或更新
            orders.setCreatetime(DateUtil.now());
            orderService.addcart(orders);
            return Result.success();
        }
    }

    @DeleteMapping("/{orderid}")
    public Result delete(@PathVariable Integer orderid){
        orderService.delete(orderid);
        return Result.success();
    }
}
